package org.bt.auth.config.runner;

import cn.hutool.crypto.SecureUtil;
import org.apache.commons.lang3.StringUtils;
import org.bt.common.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import java.security.KeyPair;

/**
 * @author zwj
 * @date 2022/12/8
 * @description TODO 生成rsa密钥对
 */
@Configuration
public class ServerRunner implements CommandLineRunner {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * Base64编码
     */
    private static final java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();

    /**
     * Base64解码
     */
    private static final java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();

    @Override
    public void run(String... args) {
        String pubKey = redisTemplate.opsForValue().get(CommonConstant.RedisKey.SERVER_PUB_KEY);
        String priKey = redisTemplate.opsForValue().get(CommonConstant.RedisKey.SERVER_PRI_KEY);
        if (StringUtils.isBlank(pubKey) || StringUtils.isBlank(priKey)) {
            KeyPair rsa = SecureUtil.generateKeyPair("RSA", 2048);
            redisTemplate.opsForValue().set(CommonConstant.RedisKey.SERVER_PUB_KEY, encoder.encodeToString(rsa.getPublic().getEncoded()));
            redisTemplate.opsForValue().set(CommonConstant.RedisKey.SERVER_PRI_KEY, encoder.encodeToString(rsa.getPrivate().getEncoded()));
        }
    }
}